<template>
  <!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
  <a-drawer
      v-model:open="visible"
      ref="employeeDetailModalRef"
      class="edit-drawer modal-fixed-bottom"
      root-class-name="root-customer-drawer"
      width="800px"
      :closable="false"
      @close="onClose"
  >
    <div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
    <div class="modal-header">{{ title }}</div>
    <a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
            @finish="onSubmit"
    >
      <a-form-item :label="$t('self.systemUser.modal.col1')" name="name">
        <a-input allow-clear v-model:value="formState.name" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.systemUser.modal.col2')" name="password">
        <a-input allow-clear v-model:value="formState.password" placeholder="" type="password" />
      </a-form-item>
      <a-form-item :label="$t('self.systemUser.modal.col3')" name="mobile">
        <a-input allow-clear v-model:value="formState.mobile" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.systemUser.modal.col4')" name="realName">
        <a-input allow-clear v-model:value="formState.realName" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.systemUser.tips21')" name="roleIds">
        <a-select mode="multiple" v-model:value="formState.roleIds" :options="roleArrOptions" :fieldNames="{label: 'roleName',value: 'id'}" />
      </a-form-item>
      <a-form-item :label="$t('self.systemUser.modal.col6')" name="status">
        <a-select v-model:value="formState.status" :options="[{ label: $t('self.systemUser.tips9'), value: 1 },{ label: $t('self.systemUser.tips10'), value: 0 }]" />
      </a-form-item>
<!--      <a-form-item :label="$t('self.systemUser.modal.col7')" name="orgId">-->
<!--        <a-select v-model:value="formState.orgId" :options="orgOptions" :fieldNames="{label: 'orgName',value: 'id'}" />-->
<!--      </a-form-item>-->

      <div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
        <a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
        <a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
      </div>

    </a-form>

  </a-drawer>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $T = proxy.$t
const $API = proxy.$API
const emit = defineEmits(['close','ok'])

const visible = ref(false)
// 模式，add新增，show查看，edit编辑
const mode = ref('add')
const labelCol = {
  style: {
    width: '150px',
  },
};
const wrapperCol = {
  span: 16,
};
const title = ref()
const formState = ref({
  "id": 0,
  "userType": 2,
  "realName": "",
  "name": "",
  "password": "",
  "status": 1,
  "mobile": "",
  "orgId": null,
  "roleIds": [], // 角色，多个用逗号隔开
})
const roleArrOptions = ref([])
const orgOptions = ref([])

const formRules = ref({
  name: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col1'),trigger: 'change'}],
  password: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col2'),trigger: 'change'}],
  mobile: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col3'),trigger: 'change'}],
  realName: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col4'),trigger: 'change'}],
  // roleIds: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col5'),trigger: 'change'}],
  status: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col6'),trigger: 'change'}],
  // orgId: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
})

onMounted(async () => {
  // orgOptions.value = await proxy.getOrgSelectList(true)
  // 获取角色下拉列表
  roleArrOptions.value = await proxy.getRoleSelectList()
})

// const getUserInfo = () => {
//   return new Promise((resolve, reject) => {
//     $API.backend.systemUser.queryUserOrgRole.post({
//       id: formState.value.id
//     }).then(res => {
//       const { objData } = res
//       sourceUserInfo.value = objData
//       resolve()
//     }).catch(err => {
//       reject(err)
//     })
//   })
// }

const getDetail = () => {
  return new Promise((resolve, reject) => {
    $API.backend.systemUser.query.post({
      id: formState.value.id
    }).then(res => {
      const { objData } = res
      formState.value.roleIds = objData.roleIdsArr ? objData.roleIdsArr : []
      // sourceUserInfo.value = objData
      resolve()
    }).catch(err => {
      message.error(err.msg);
      reject(err)
    })
  })
}

const onSubmit = (values) => {
  const params = { ...formState.value }
  params.roleIds = !params.roleIds ? '' : params.roleIds.join(',')
  if(mode.value === 'add') {
    // 添加
    $API.backend.systemUser.add.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error($T('self.message.error'))
    })
  }else{
    // 修改
    $API.backend.systemUser.edit.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error(err.msg);
    })
  }
};

const onReset = () => {
  // 清空内容
  formState.value = {
    "id": 0,
    "userType": 2,
    "realName": "",
    "name": "",
    "password": "",
    "status": 1,
    "mobile": "",
    "orgId": null,
  }
}

const onClose = () => {
  onReset()
  visible.value = false
  emit('close')
}

const add = () => {
  title.value = $T('self.systemUser.tips13')
  mode.value = 'add'
  visible.value = true
}

const edit = async (record) => {
  title.value = $T('self.systemUser.tips24')
  mode.value = 'edit'
  visible.value = true
  // formState.value = record
  const params = { ...record }
  params.roleIds = params.roleIds ? params.roleIds.split(',') : [] // 在每个逗号(,)处进行分解
  $TOOL.array.cloneExistKey(formState.value, params)



  // 获取当前用户已经选择的角色
  getDetail()
  // console.log(formState.value)
}

const show = (record) => {
  mode.value = 'show'
  visible.value = true
  formState.value = record
}

// 子组件中要通过defineExpose将方法暴露给父组件
defineExpose({
  add,
  edit,
  show
})
</script>

<style lang="scss" scoped>
.edit-drawer {
  position: relative;
  .closeable {
    @include closeable;
  }
}
</style>
